Function.prototype.getName = function() {
	return this.name || this.toString().match(/function\s*([^(]*)\(/)[1]
}
var hot1;
$(document).ready(function() {
	var hotSetting = {
		contextMenu: {
			callback: function(key, options) {
				var startCol = options.start.col,
					startRow = options.start.row;
				if (key === 'setVal') {
					var cellMeta = this.getCellMeta(startRow, startCol);
					cellMeta.readOnly = true;
					setTimeout(function() {
						showDbFunDialog(startRow, startCol);
					}, 100);
				}
			},
			items: {
				"row_above": {
					name: '向上插入一行'
				},
				"row_below": {
					name: '向下插入一行'
				},
				"hsep1": "---------",
				"col_left": {
					name: '左侧插入一列'
				},
				"col_right": {
					name: '右侧插入一列'
				},
				"hsep2": "---------",
				"remove_row": {
					name: '删除行'
				},
				"remove_col": {
					name: '删除列'
				},
				"hsep3": "---------",
				"alignment": {
					name: '对齐'
				},
				"hsep4": "---------",
				"mergeCells": {
					name: '合并单元格'
				},
				"hsep5": "---------",
				"setVal": {
					name: '设置动态值'
				}
			}
		}
	};

	function showDbFunDialog( startRow, startCol) {
		var open = function() {
			var cellMeta = hot1.getCellMeta(startRow, startCol);
			var code = cellMeta.code;
			var backType = cellMeta.backtype;
			// 设置脚本
			$('#setVal', this).val(code);
			$('#freeDataPreview').parent().hide();
			$('#setPoints', this).val('');

			if (backType) {
				$('input[name="backType"][value="' + backType + '"]', this).prop('checked', true).trigger('change');
				if (backType == 'table') {
					$('#setPoints', this).val(cellMeta.points);
				}
			} else {
				$('input[name="backType"]:first', this).prop('checked', true).trigger('change');
			}
			$(this).css('z-index', 1000);
			$('.ui-widget-overlay:last').css('z-index', 1000);
		};
		var ok = function() {
			var $_setVal = $('#setVal', this);
			$_setVal.focus();
			var val = $_setVal.val();
			var backType = $('input[name="backType"]:checked', this);

			if (val) {
				var cellMeta = hot1.getCellMeta(startRow, startCol);

				cellMeta.code = val;
				cellMeta.backtype = backType.val();
				if (cellMeta.backtype == 'table') {
					cellMeta.points = $('#setPoints', this).val();
				}
				var classNames = cellMeta.className;
				var defClassName = hot1.getSettings().className;
				if (classNames.indexOf('dbFun') == -1) {
					cellMeta.className = defClassName + ' dbFun';
				}
				cellMeta.readOnly = true;

				$(this).dialog("close");
				hot1.render();
			} else {
				alert('脚本不能为空');
			}
		}

		$('#freeTabSetVal').dialog({
			title: '设置值',
			width: 600,
			modal: true,
			show: true,
			resizable: false,
			open: open,
			buttons: [{
				text: "确定",
				click: ok
			}, {
				text: "取消",
				click: function() {
					$(this).dialog("close");
				}
			}]
		});
	}

	function preview(type, code) {
		function doSome(data) {
			var tmpData = [];
			if (type == 'signValue') {
				tmpData.push(['单列值']);
				tmpData.push([data]);
			} else if (type == 'smartParam') {
				headName = '参数值';
				tmpData.push(['参数值']);
				tmpData.push([SimpleDataHandler.getSmartParamName(code, data)]);
			}
			data = tmpData.length == 0 ? data : tmpData;

			var previewId = "#freeDataPreview";
			$(previewId + ' table').remove();
			jQuery.jsontotable(data, {
				id: previewId,
				header: true,
				excel: true
			});
			$(previewId + ' table').addClass('stripe');
			$(previewId).parent().show();
		}
		var url;
		var sendData = {
			pageId: parent.pageId,
			code: code
		};
		if (type == 'signValue') {
			url = 'simpleData/getSimpleData';
		} else if (type == 'table') {
			url = 'table/getTable'
		}

		parent.ck.util.sendAjax({
			url: url,
			data: sendData
		}, doSome);
	}

	$('#freeDataPreviewBtn').click(function() {
		var backType = $('input[name="backType"]:checked', $(this).parents('#freeTabSetVal')).val();
		var setVal = $('#setVal').val();
		preview(backType, setVal);
	});

	// 输入值单选按钮事件
	$('#freeTabSetVal input[name="backType"]').bind('change', function() {
		var val = this.value;
		var setPointParent = $('#freeTabSetVal #setPoints').parent();
		if (val == 'table') {
			setPointParent.show();
		} else {
			setPointParent.hide();
		}
	});


	var option = {
		width: 825,
		height: 420,
		colHeight: 24,
		colHeaders: true,
		rowHeaders: true,
		contextMenu: true,
		minSpareRows: 1,
		manualColumnResize: true,
		manualRowResize: true,
		mergeCells: true,
		className: "htCenter htMiddle"
	};
	var data1 = (function() {
		var result = [];
		for (var row = 0; row < 20; row++) {
			var lines = [];
			for (var col = 0; col < 15; col++) {
				lines.push('');
			}
			result.push(lines);
		}
		return result;
	})();
	var mergeCells = parent.$_doc.data('freeMergeCells');
	if (mergeCells) {
		option = $.extend(true, option, {
			mergeCells: mergeCells
		});
	}
	var data = parent.$_doc.data('freeDatas');
	if (data) {
		option = $.extend(true, option, {
			data: data
		});
	} else {
		option = $.extend(true, option, {
			data: data1
		});
	}

	var $content = document.getElementById("handsontable");
	hot1 = new Handsontable($content, option);

	hot1.addHook('beforeKeyDown', function(event) {
		var keyCode = event.keyCode;
		var isCtrlDown = false;
		if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) {
			isCtrlDown = true;
		}
		var selected = this.getSelected();
		if (selected && selected.length > 0) {
			var startRow = selected[0],
				startCol = selected[1],
				endRow = selected[2],
				endCol = selected[3];
			if (keyCode == 46) { // delete
				if (startRow == endRow && startCol == endCol) { // 至选中一个单元格
					var cellMeta = this.getCellMeta(startRow, startCol);
					cellMeta.className = this.getSettings().className;

					delete cellMeta.code;
					delete cellMeta.backtype;
					cellMeta.readOnly = false;
				}
			} else if (isCtrlDown && (event.keyCode === Handsontable.helper.KEY_CODES.C)) { // ctrl
				var cellMeta = hot1.getCellMeta(startRow, startCol);
				if (cellMeta.readOnly || cellMeta.className.indexOf('expression') >= 0) {
					$('body').data('copyMeta', cellMeta);
				} else {
					$('body').removeData('copyMeta');
				}
			}
		}
	});

	function coverRenderer(instance, td, row, col, prop, value, cellProperties) {
		var classNames = cellProperties.className;
		td.className = classNames;
		Handsontable.Dom.empty(td);
		return td;
	}

	hot1.addHook('afterChange', function(changes, source) {
		var row = changes[0][0],
			col = changes[0][1],
			oldVal = changes[0][2],
			newVal = changes[0][3];

		if (source == 'edit') {
			// 判断是否为excel函数
			var isFun = newVal.indexOf('=') == 0;
			// 引用系统函数值
			var isSysFun = newVal.indexOf('#') == 0;
			var cellMeta = hot1.getCellMeta(row, col);
			var classNames = cellMeta.className;
			var defClassName = hot1.getSettings().className;

			if (isFun) {
				cellMeta.renderer = coverRenderer;
				cellMeta.code = newVal;
				if (classNames.indexOf('expression') == -1) {
					cellMeta.className = defClassName + ' expression';
				}
				hot1.render();
			} else if (isSysFun) {
				if (classNames.indexOf('sysFun') == -1) {
					cellMeta.className = defClassName + ' sysFun';
				}
			} else { //清除数据样式
				cellMeta.className = defClassName;
			}
		} else if (source == 'paste') {
			var copyMeta = $('body').data('copyMeta');
			if (copyMeta) {
				hot1.setCellMetaObject(row, col, copyMeta);
				hot1.render();
			}
		}
	});

	var cellMetas = parent.$_doc.data('freeCellMetas');
	if (cellMetas) {
		for (var i = 0; i < cellMetas.length; i++) {
			var cellMeta = cellMetas[i];
			var col = cellMeta.col,
				row = cellMeta.row,
				code = cellMeta.code,
				backtype = cellMeta.backtype,
				myclass = cellMeta.myclass,
				rendererName = cellMeta.rendererName;

			var hotCellMeta = hot1.getCellMeta(row, col);

			if (rendererName) {
				hotCellMeta.renderer = eval(rendererName);
			}

			hotCellMeta.code = code;
			if (myclass == 'dbFun') {
				hotCellMeta.backtype = backtype;

				if (backtype == 'table') {
					var points = cellMeta.points;
					hotCellMeta.points = points;
				}
				hot1.getCellMeta(row, col).readOnly = true;
			}

			if (cellMeta.className) {
				hotCellMeta.className = cellMeta.className
			} else if (myclass) {
				hotCellMeta.className = hotCellMeta.className + ' ' + myclass;
			}
		}
	}
	hot1.updateSettings(hotSetting);

	// 添加双击事件
	function bindDbClickForTable() {
		var $_tbody = $('.ht_master .htCore tbody', hot1.rootElement);
		$_tbody.on('dblclick', 'td', function() {
			var selected = hot1.getSelected();
			if (selected && selected.length > 0) {
				var startRow = selected[0],
					startCol = selected[1],
					endRow = selected[2],
					endCol = selected[3];
				if (startRow == endRow && startCol == endCol) {
					var cellMeta = hot1.getCellMeta(startRow, startCol);
					var classNames = cellMeta.className;
					if (classNames.indexOf('dbFun') >= 0) {
						showDbFunDialog(startRow, startCol);
					} else if (classNames.indexOf('expression') >= 0) {
						var code = cellMeta.code;
						if (code && code != "") {
							$('.handsontableInput').val(code);
						}
					}
				}
			}
		});
	}
	setTimeout(bindDbClickForTable, 100);

	function buildHtml(hot1, data, mergedCellInfos) {
		var otherData = $.extend(true, [], data);

		var table = $('<table></table>');
		// 总行数
		var countRow = hot1.countRows();
		// 总列数
		var countCol = hot1.countCols();

		var cellMetas = [];

		for (var row = 0; row < countRow; row++) {
			var newTr = $('<tr></tr>');
			for (var col = 0; col < countCol; col++) {
				var cellData = hot1.getDataAtCell(row, col);

				var defCellMeta = hot1.getSettings().className;
				var cellMeta = hot1.getCellMeta(row, col);
				var className = cellMeta.className;
				cellData = cellData == undefined ? '' : cellData;
				if (cellData) {
					// 去掉 png 后缀，解决之前版本的遗留问题
					if (cellData.indexOf('png') >= 0) {
						cellData = '';
					}
				} else {
					cellData = '';
				}

				var $cell = $('<td class="' + className + '">' + cellData + '</td>');
				newTr.append($cell);

				var renderer = cellMeta.renderer;
				var code = cellMeta.code;
				var obj;
				if (code) {
					obj = {
						row: row,
						col: col,
						code: code
					}

					if (renderer) {
						var rendererName = renderer.getName();
						obj = $.extend(obj, {
							rendererName: rendererName
						});
					}

					$cell.attr('code', code);
					if ($cell.hasClass('dbFun')) {
						var backtype = cellMeta.backtype;
						$cell.attr('backtype', backtype);

						obj = $.extend(obj, {
							backtype: backtype,
							myclass: 'dbFun'
						});

						if (backtype == 'table') {
							var points = cellMeta.points;
							obj = $.extend(obj, {
								points: points
							});
							$cell.attr('points', points);
						}
					} else if ($cell.hasClass('expression')) {
						obj = $.extend(obj, {
							myclass: 'expression'
						});
					} else if ($cell.hasClass('sysFun')) {
						obj = $.extend(obj, {
							myclass: 'sysFun'
						});
					}
				}

				// 放入修改的对齐样式
				if (defCellMeta != className) {
					if (obj) {
						obj = $.extend(obj, {
							className: className
						});
					} else {
						obj = {
							row: row,
							col: col,
							className: className
						};
					}
				}

				if (obj) {
					cellMetas.push(obj);
					obj = undefined;
				}
			}
			table.append(newTr);
		}

		for (var index = 0; index < mergedCellInfos.length; index++) {
			var mergedCellInfo = mergedCellInfos[index];
			var mRow = mergedCellInfo.row,
				mRowspan = mergedCellInfo.rowspan;
			var mCol = mergedCellInfo.col,
				mColspan = mergedCellInfo.colspan;

			var selectRows = table.find('tr').slice(mRow, (mRowspan + mRow));
			var isFirst = true;
			$.each(selectRows, function(i, n) {
				var $_this = $(n);
				if (isFirst) {
					isFirst = false;
					var needTds = $(n).find('td').slice(mCol, (mCol + mColspan));
					needTds.filter(':first').attr('rowspan', mRowspan).attr('colspan', mColspan).attr('data-col', mColspan - 1).attr('data-type', 'head').css('height', (mRowspan * 24) + 'px');
					needTds.filter(':not(:first)').addClass('delspan');
				} else {
					$(n).find('td').slice(mCol, (mCol + mColspan)).addClass(
						'delspan');

					var findTd = $(n).find('td').slice(mCol - 1, mCol);
					if (findTd.size() > 0) {
						findTd.attr('data-type', 'head');
					} else {
						findTd = $(n).find('td').slice((mCol + mColspan), (mCol + mColspan + 1));
						findTd.attr('data-type', 'bottom');
					}
					findTd.attr('data-col', mColspan);
				}
			});
		}
		table.find('.delspan').hide();

		// 去除png 后缀
		for (var i = 0; i < otherData.length; i++) {
			var datas = otherData[i];
			for (var y = 0; y < datas.length; y++) {
				var d = otherData[i][y];
				if (d && d.indexOf('png') >= 0) {
					d = '';
					otherData[i][y] = d;
				}
			}
		}

		return [table, otherData, cellMetas];
	}

	// 确定按钮
	$('#freeSucssBtn').click(function() {
		var parentObj = parent;
		var $_doc = parent.$_doc;

		var mergedCellInfos = [];
		if (hot1.mergeCells) {
			mergedCellInfos = hot1.mergeCells.mergedCellInfoCollection.slice(0); // 拷贝
		}

		var data = hot1.getData().slice(0); // 拷贝

		var freeTabs = buildHtml(hot1, data, mergedCellInfos);
		var element = $_doc.data('freeElement');
		var id = $_doc.data('freeId');

		$_doc.data(id, {
			data: freeTabs[1],
			mergedCellInfos: mergedCellInfos,
			cellMetas: freeTabs[2]
		});
		var insertEle = element.findOne('.simplebox-content');
		var findEle = insertEle.getChildren();
		var count = findEle.count();
		if (count > 0) {
			for (var i = 0; i < count; i++) {
				findEle.getItem(0).remove();
			}
		}

		var freeTable = freeTabs[0];
		var hideFreeTab = freeTable.clone().addClass('hideClass').hide();

		var freeHtml = freeTable[0].outerHTML;
		var hideHtml = hideFreeTab[0].outerHTML;

		parent.ck.util.sendAjax({
			url: 'freeTable/getRealTabHtmlByFreeTabHtml',
			data: {
				pageId: parent.pageId,
				freeTabHtml: encodeURIComponent(freeHtml),
				t: new Date().getTime()
			}
		}, function(data) {
			if(parentObj){
				parentObj.jQuery.fn.insertCkFreeTableHtml(data.html, hideHtml, insertEle, data.simpleUseArgs);
			}
		});

		if($_doc.data('freeForInit')){
			element.show();
		}
		parent.jQuery.fancybox.close();
	});

	function freeCancel() {
		var $_doc = parent.$_doc;

		var element = $_doc.data('freeElement');
		var forInit = $_doc.data('freeForInit');
		if (forInit) {
			element.getParent().remove();
		}

		parent.jQuery.fancybox.close();
	}

	// 取消按钮
	$('#freeCancel').click(freeCancel);

	$('#header .freeClose').hover(function() {
		$(this).css('background-image', 'url(resources/jquery-ui-bootstrap3/css/images/ui-icons_454545_256x240.png)');
	}, function() {
		$(this).css('background-image', 'url(resources/jquery-ui-bootstrap3/css/images/ui-icons_888888_256x240.png)');
	}).bind('click', freeCancel);
});